#!groovy

def call(String jenkinsLabel,String projectName) {
    echo projectName
    echo jenkinsLabel
    node("${jenkinsLabel}") {
        def KUTUI_GROUP="https://push.xuthus.cc/group"
        def DEPLOY_VERSION="SNAPSHOT-1.${BUILD_NUMBER}"

        try {
            def map = [:]
            map.put('HPHZPT-finance', "5001:5005")
            map.put('HPHZPT-goods', "5002:5005")
            map.put('HPHZPT-goods-search', "5003:5005")
            map.put('HPHZPT-interface', "5004:5005")
            map.put('HPHZPT-member', "5005:5005")
            map.put('HPHZPT-modules', "5006:5005")
            map.put('HPHZPT-mq-consumer', "5007:5005")
            map.put('HPHZPT-mq-producer', "5008:5005")
            map.put('HPHZPT-order', "5009:5005")
            map.put('HPHZPT-pay', "5010:5005")
            map.put('HPHZPT-policy-search', "5011:5005")
            map.put('HPHZPT-rebate', "5012:5005")
            map.put('HPHZPT-require', "5013:5005")
            map.put('HPHZPT-system', "5014:5005")
            def PROJECT_NAME = projectName.toLowerCase()
            def DEBUG_PORT = map.get(projectName)

            def NODE_HOSTNAME = 'host104'
            def DB_NAME = 'zhongyuan-dev'
            def DUBBO_REGISTRY_ADDRESS = '10.21.1.104:2181'
            if (env.BRANCH_NAME == "master") {
                DEBUG_PORT = "1" + "" + DEBUG_PORT
                NODE_HOSTNAME = 'host102'
                DB_NAME = 'zhongyuan'
                DUBBO_REGISTRY_ADDRESS = '10.21.1.101:2181'
                DEPLOY_VERSION="RELEASE-1.${BUILD_NUMBER}"
            }

            def GIT_URL = 'https://gitee.com/crowdmall/test7.git'
            def ARTI_IPPORT = '10.21.1.105:8082'
            ////////////////////////////以下是模板
            def SONAR_SOURCES = 'RPC/' + projectName
            def POM_PATH = SONAR_SOURCES + '/pom.xml'
            def artiServer = Artifactory.newServer url: 'http://'+ARTI_IPPORT+'/artifactory/', credentialsId: 'artifactory-credential'
            def ARTIFACTORY_API_KEY = 'AKCp8hyEaWNZwwwPHE5aqgfphwFjWYU3yEENmgZbtTNoQsa6zjMUS99D3UqA4FbGo1kUmH76x'
            def ARTIFACTORY_URL = 'http://'+ARTI_IPPORT+'/artifactory/'
            def rtMaven = Artifactory.newMavenBuild()
            def buildInfo = Artifactory.newBuildInfo()
            def RESOLVE_SNAPSHOT_REPO = 'libs-snapshot'
            def RESOLVE_RELEASE_REPO = 'libs-release'
            def DEPLOY_SNAPSHOT_REPO = 'libs-snapshot-local'
            def DEPLOY_RELEASE_REPO = 'libs-release-local'
            def PROMOTION_SOURCE_REPO = 'libs-snapshot-local'
            def PROMOTION_TARGET_REPO = 'libs-release-local'
            def MAVEN_GOALS = 'clean install -DskipTests'
            //sonar
            def SONAR_HOST_URL = 'http://10.21.1.103:9000'
            def SONAR_SERVER = 'sonar'
            def SONAR_SCANNER_TOOL = 'sonar'
            def SONAR_PROJECT_KEY = "${JOB_NAME}".replace("/", "_") + "_" + projectName
            //git
            def GIT_CREDENTIALS_ID = 'crowdmall'
            def mavenHome = '/root/.m2'
            if (env.BRANCH_NAME == "master") {
                //测试分支才需要deploy
                mavenHome = '/root/.m2-test'
            }
            docker.image(ARTI_IPPORT+'/docker-remote/maven:3.3.3').inside("-v /root/.sonarqube/sonar:/sonar -v ${mavenHome}:/root/.m2 -v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker --user root") {
                withEnv(['MAVEN_HOME=/usr/share/maven/', 'JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64', 'PATH+MAVEN=${env.JAVA_HOME}/bin:${env.MAVEN_HOME}/bin']) {

                    stage('Prepare') {
                        echo "${env.BRANCH_NAME}"
                        echo "环境准备"
                        rtMaven.resolver server: artiServer,
                                releaseRepo: RESOLVE_RELEASE_REPO,
                                snapshotRepo: RESOLVE_SNAPSHOT_REPO
                        rtMaven.deployer server: artiServer,
                                releaseRepo: DEPLOY_RELEASE_REPO,
                                snapshotRepo: DEPLOY_SNAPSHOT_REPO
                    }
                    stage('SCM') {
                        git url: GIT_URL,
                                branch: env.BRANCH_NAME,
                                changelog: true,
                                credentialsId: GIT_CREDENTIALS_ID
                    }
                    stage('env capture') {
                        echo "收集系统变量"
                        buildInfo.env.capture = true
                    }
                    //Sonar 静态代码扫描
                    stage('Sonar') {
                        try {
                            if (env.BRANCH_NAME == "master") {
                                def scannerHome = tool SONAR_SCANNER_TOOL;
                                withSonarQubeEnv(SONAR_SERVER) {
                                    sh "${scannerHome}/bin/sonar-scanner -Dsonar.language=java -Dsonar.projectKey=${SONAR_PROJECT_KEY} -Dsonar.sources=${SONAR_SOURCES} -Dsonar.host.url=${SONAR_HOST_URL} -Dsonar.java.binaries=*"
                                }
                            }
                        } catch (exception) {
                            echo "无法完成静态代码扫描" + exception
                        }
                    }
                    //添加sonar扫描结果到包上
                    stage("Sonar Quality Gate") {
                        try {
                            if (env.BRANCH_NAME == "master") {
                                timeout(time: 1, unit: 'MINUTES') {
                                    sleep 20
                                    // Just in case something goes wrong, pipeline will be killed after a timeout
                                    def qg = waitForQualityGate()
                                    // Reuse taskId previously collected by withSonarQubeEnv
                                    if (qg.status != 'OK') {
                                        error "Pipeline aborted due to quality gate failure: ${qg.status}"
                                    } else {
                                        //获取sonar扫描结果
                                        def surl = "${SONAR_HOST_URL}/api/measures/component?componentKey=${SONAR_PROJECT_KEY}&metricKeys=alert_status,quality_gate_details,coverage,new_coverage,bugs,new_bugs,reliability_rating,vulnerabilities,new_vulnerabilities,security_rating,sqale_rating,sqale_index,sqale_debt_ratio,new_sqale_debt_ratio,duplicated_lines_density&additionalFields=metrics,periods"
                                        def response = httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', ignoreSslErrors: true, url: surl

                                        def propssonar = readJSON text: response.content
                                        if (propssonar.component.measures) {
                                            propssonar.component.measures.each { measure ->
                                                def val
                                                if (measure.periods) {
                                                    val = measure.periods[0].value
                                                } else {
                                                    val = measure.value
                                                }
                                                rtMaven.deployer.addProperty("sonar.quality.${measure.metric}", val)
                                            }
                                        }

                                        //增加sonar扫描结果到artifactory
                                        rtMaven.deployer.addProperty("qulity.gate.sonarUrl", SONAR_HOST_URL + "/dashboard/index/" + SONAR_PROJECT_KEY)
                                    }
                                }
                            }
                        } catch (exception) {
                            echo '没有拿到静态代码扫描报告' + exception
                        }
                    }
                    stage('add jiraResult') {
                        if (env.BRANCH_NAME == "master") {
                            echo "add jiraResult"
                            //def requirements = getRequirementsIds();
                            //echo "requirements : ${requirements}"

                            //def revisionIds = getRevisionIds();
                            //echo "revisionIds : ${revisionIds}"
                            //rtMaven.deployer.addProperty("project.issues", requirements).addProperty("project.revisionIds", revisionIds)
                        }
                    }
                    //maven 构建
                    stage('mvn build') {
                        rtMaven.deployer.deployArtifacts = false
                        rtMaven.run pom: POM_PATH, goals: MAVEN_GOALS, buildInfo: buildInfo
                    }
                    stage('package deploy to aitifactory') {
                        if (env.BRANCH_NAME == "master") {
                            rtMaven.deployer.deployArtifacts buildInfo
                            artiServer.publishBuildInfo buildInfo
                        }
                    }
                    //进行测试
                    stage('basic test') {
                        if (env.BRANCH_NAME == "master") {
                            echo "add test step"
                        }
                    }
                    stage('xray scan') {
                        if (env.BRANCH_NAME == "master") {
                            def xrayConfig = [
                                    'buildName'  : buildInfo.name,
                                    'buildNumber': buildInfo.number,
                                    'failBuild'  : false
                            ]
                            //def xrayResults = artiServer.xrayScan xrayConfig
                            //echo xrayResults as String
                        }
                    }
                    //promotion操作，进行包的升级
                    stage('promotion') {
                        if (env.BRANCH_NAME == "master") {
                            def promotionConfig = [
                                    'buildName'          : buildInfo.name,
                                    'buildNumber'        : buildInfo.number,
                                    'targetRepo'         : PROMOTION_TARGET_REPO,
                                    'comment'            : 'this is the promotion comment',
                                    'sourceRepo'         : PROMOTION_SOURCE_REPO,
                                    'status'             : 'Released',
                                    'includeDependencies': false,
                                    'failFast'           : true,
                                    'copy'               : true
                            ]
                            artiServer.promote promotionConfig
                        }
                    }

                    stage('build && push') {
                        if (map.containsKey(projectName)) {
                            withCredentials([usernamePassword(credentialsId: '1c6eb9ba-7a49-4611-89b3-35feb3c80725', passwordVariable: 'password', usernameVariable: 'username')]) {
                                sh "cd ${SONAR_SOURCES}/HPHZPT-service-impl &&" +
                                        "docker login -u ${username} -p ${password} ${ARTI_IPPORT} && " +
                                        "docker build -f ./Dockerfile -t ${ARTI_IPPORT}/docker-local/${PROJECT_NAME}:${DEPLOY_VERSION} .&&" +
                                        "docker push ${ARTI_IPPORT}/docker-local/${PROJECT_NAME}:${DEPLOY_VERSION}"
                            }
                        }
                    }

                    stage('deploy') {
                        if (map.containsKey(projectName)) {
                            sh '''
                                export SERVICE_IMAGE='''+ARTI_IPPORT+'''/docker-local/''' + "${PROJECT_NAME}" + ''':''' + "${DEPLOY_VERSION}" + '''
                                export DEBUG_PORT=''' + "${DEBUG_PORT}" + '''
                                export DUBBO_REGISTRY_ADDRESS=''' + "${DUBBO_REGISTRY_ADDRESS}" + '''
                                export DB_NAME=''' + "${DB_NAME}" + '''
                                export NODE_HOSTNAME=''' + "${NODE_HOSTNAME}" + '''
                                docker stack deploy -c ./jenkins/docker-compose.yml --with-registry-auth ''' + "${PROJECT_NAME}"+'''_'''+"${env.BRANCH_NAME}"

                            //添加元数据
                            def pom = readMavenPom file: SONAR_SOURCES+'/HPHZPT-service-impl/pom.xml'
                            def latestVersionUrl = "${ARTIFACTORY_URL}api/search/latestVersion?g=${pom.parent.groupId.replace(".","/")}&a=${pom.artifactId}&v=${pom.parent.version}&repos=${PROMOTION_TARGET_REPO}"
                            def latestVersionUrlResponse = httpRequest consoleLogResponseBody: true,
                                    customHeaders: [[name: 'X-JFrog-Art-Api',
                                                     value: ARTIFACTORY_API_KEY]],
                                    ignoreSslErrors: true,
                                    url: latestVersionUrl
                            def jarLatestVersion = latestVersionUrlResponse.content
                            httpRequest httpMode: 'PUT',
                                    consoleLogResponseBody: true,
                                    customHeaders: [[name: 'X-JFrog-Art-Api', value: ARTIFACTORY_API_KEY]],
                                    url: "${ARTIFACTORY_URL}api/storage/${PROMOTION_TARGET_REPO}/${pom.parent.groupId.replace(".","/")}/${pom.artifactId}/${pom.parent.version}/${pom.artifactId}-${jarLatestVersion}.jar?properties=deploy.tool=dockerswarm;deploy.env=host102"

                        }
                    }
                }
            }
            echo "2"
            withCredentials([string(credentialsId: 'kutui-token', variable: 'KUTUI_KEY')]) {
                echo "完成构建，发qq"
                sh "curl ${KUTUI_GROUP}/${KUTUI_KEY}?c=构建状态:SUCCESS:$projectName:${DEPLOY_VERSION}-${env.BRANCH_NAME}"
            }
        }catch(exception1){
            echo "1"
            withCredentials([string(credentialsId: 'kutui-token', variable: 'KUTUI_KEY')]) {
                echo "构建异常，发qq"
                sh "curl ${KUTUI_GROUP}/${KUTUI_KEY}?c=构建状态:FAILED:$projectName:${DEPLOY_VERSION}-${env.BRANCH_NAME}"
            }
            throw exception1
        }
    }
}